<?php

class userbaseAction extends frontendAction {

    public function _initialize(){
        parent::_initialize();
        //访问者控制
        if (!$this->visitor->is_login && !in_array(ACTION_NAME, array('login', 'register', 'binding', 'ajax_check'))) {
            IS_AJAX && $this->ajaxReturn(0, L('login_please'));

            if(isset($_GET['state']) && $_GET['state']){   //此参数来自微信，如果有值，说明是在微信公众平台中打开的
                //微信回调,openid
                $code = $_GET['code'];
                $weixinAccess = M('access');

                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".C('WEIXIN_APPID')."&secret=".C('WEIXIN_APPSECRET')."&code=".$code."&grant_type=authorization_code";
                $json_res = json_decode($this->send_get_req($url),true);
                if(isset($json_res['errcode'])){
                    $this->_404('/');
                }

                $access = $weixinAccess->where("openid='{$json_res['openid']}'")->find();
                if($access){   //已存在此用户，直接登录
                    $this->visitor->login($access['uid'], 1);
                    return true;
                    //$this->redirect($_SERVER['REQUEST_URI']);
                }

                $getUserUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$json_res['access_token']."&openid=".$json_res['openid']."&lang=zh_CN";
                $json_res = json_decode($this->send_get_req($getUserUrl),true);
                if(!isset($json_res['errcode'])){
                    $user = D('user');
                    $data = array('username'=>$json_res['nickname'],
                            'gender'=>$json_res['sex'],
                            'avatar'=>$json_res['headimgurl'],
                            'province'=>$json_res['province'],
                            'city'=>$json_res['city'],
                            'reg_time'=>time(),
                        );
                    $uid = $user->add($data);

                    $data = array(
                            'openid'   => $json_res['openid'],
                            'userinfo' => json_encode($json_res),
                            'uid'      => $uid
                        );
                    $res = $weixinAccess->add($data);
                    if($res){
                        //$this->visitor->login($access['uid'], 1);
                        // $this->redirect($_SERVER['REQUEST_URI']);
                        return true;
                    }else{
                        echo "微信登录失败";exit;
                    }

                }
            }else{
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx88c25b242cf211b2&redirect_uri=".rawurlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'])."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                header('location:'.$url);exit;
            }
        }
        $this->online_user = $this->visitor->info;
        $this->_curr_menu(ACTION_NAME);
        $this->assign('address_str', $this->fetch_area(1));

    }

    protected function _curr_menu($menu = 'index') {
        $menu_list = $this->_get_menu();
        $this->assign('user_menu_list', $menu_list);
        $this->assign('user_menu_curr', $menu);
    }

    private function _get_menu() {
        $menu = array();
        $menu = array(
            'setting' => array(
                'text' => '帐号设置',
                'submenu' => array(
                    'index' => array('text'=>'基本信息', 'url'=>U('user/index')),
                    'password' => array('text'=>'修改密码', 'url'=>U('user/password')),
                    'bind' => array('text'=>'帐号绑定', 'url'=>U('user/bind')),
                    'custom' => array('text'=>'个人封面', 'url'=>U('user/custom')),
                    'address' => array('text'=>'收货地址', 'url'=>U('user/address')),
                )
            ),
            'score' => array(
                'text' => '积分帐户',
                'submenu' => array(
                    'order' => array('text'=>'积分订单', 'url'=>U('score/index')),
                    'logs' => array('text'=>'积分记录', 'url'=>U('score/logs')),
                )
            ),
            'message' => array(
                'text' => '消息中心',
                'submenu' => array(
                    'message' => array('text'=>'我的私信', 'url'=>U('message/index')),
                    'system' => array('text'=>'系统通知', 'url'=>U('message/system')),
                )
            )
        );
        return $menu;
    }
}